package cn.geekyspace.scanhive.common.util;

import com.fazecast.jSerialComm.SerialPort;
import lombok.extern.slf4j.Slf4j;

import java.io.OutputStream;
import java.util.Arrays;
import java.util.Scanner;

@Slf4j
public class PLCDataSender {

    private static final String PORT_NAME = "COM1"; // 串口名称

    public static void main(String[] args) {
        PLCDataSender sender = new PLCDataSender();
        sender.sendDataToSerialPort();
    }

    public void sendDataToSerialPort() {
        SerialPort port = SerialPort.getCommPort(PORT_NAME);

        // 提示用户输入16进制数据
        byte[] dataToSend = readDataFromConsole();
        if (dataToSend == null || dataToSend.length == 0) {
            log.error("未输入有效的数据！");
            return;
        }

        // 尝试打开串口并设置参数
        if (port.openPort()) {
            try {
                // 设置串口参数
                port.setComPortParameters(9600, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
                port.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 1000, 0);

                // 获取输出流并发送数据
                OutputStream outputStream = port.getOutputStream();
                outputStream.write(dataToSend);
                outputStream.flush();

                log.info("已发送数据: {}", Arrays.toString(dataToSend));

            } catch (Exception e) {
                log.error("发送数据时发生错误: {}", e.getMessage());
            } finally {
                port.closePort(); // 发送完数据后关闭串口
            }
        } else {
            log.error("无法打开串口 {}！", PORT_NAME);
        }
    }

    /**
     * 从控制台读取16进制数据并转换为字节数组
     *
     * @return 字节数组
     */
    private byte[] readDataFromConsole() {
        System.out.println("请输入要发送的16进制数据（以空格分隔，例如：7D 00 7E 00 7F 00 80 00 81 00 1E 00）：");
        Scanner scanner = new Scanner(System.in);
        String hexInput = scanner.nextLine();

        try {
            // 拆分输入的16进制字符串并转换为字节数组
            String[] hexValues = hexInput.trim().split("\\s+");
            byte[] data = new byte[hexValues.length];
            for (int i = 0; i < hexValues.length; i++) {
                data[i] = (byte) Integer.parseInt(hexValues[i], 16);
            }
            return data;
        } catch (NumberFormatException e) {
            log.error("输入的16进制数据格式错误：{}", hexInput);
            return null;
        }
    }
}
